package com.jt.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.jt.dao.UserMapper;
import com.jt.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;

import java.sql.SQLIntegrityConstraintViolationException;
import java.util.List;

@Service
public class UserServiceImpl implements UserService{
    @Autowired
    private UserMapper userMapper;

    @Override
    public List<User> findAll() {

        return userMapper.selectList(null);
    }

    @Override
    public User findUserById(int id) {
        return userMapper.selectById(id);
    }

    @Override
    public List<User> finUserByNameAndSex(User user) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>(user);
        return userMapper.selectList(userQueryWrapper);
    }

    @Override
    public List<User> findUserByNameAndAge(User user) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("name", user.getName()).gt("age", user.getAge());
        return userMapper.selectList(userQueryWrapper);
    }

    @Override
    public List<User> findUserBySexAndAge(User user) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("sex", user.getSex()).gt("age", user.getAge());
        return userMapper.selectList(userQueryWrapper);
    }

    @Override
    public List<User> findUserByNameAndSexAndAge(User user) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>(user);
        return userMapper.selectList(userQueryWrapper);
    }

    @Override
    public Integer deleteById(Integer id) {
        return userMapper.deleteById(id);
    }

    /**
     * json互转user对象
     * 1.user对象转化为json  @ResponBody
     * 2.json转化为user对象  @RequestBody
     * @param user
     * @return
     */
    @Override
    public Integer saveUser(User user) {
        return userMapper.insert(user);
    }

    @Override
    public Integer updateById(User user) {
        return userMapper.updateById(user);
    }

    @Override
    public Integer updateByName(String name, User user) {
        UpdateWrapper<User> userUpdateWrapper = new UpdateWrapper<>();
        userUpdateWrapper.eq("name", name);
                                //set,      where
        return userMapper.update(user, userUpdateWrapper);
    }
}
